//
//  BCUserHeadPortraitController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/27.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCUserHeadPortraitController.h"

//图片选择控制器
#import <TZImagePickerController.h>
//拍照
#import "BCTakePhotoController.h"
//
#import "BCAlbumController.h"
//savephoto
#import "BCSavePhotoManager.h"
//
#import "UIAlertController+Authorization.h"

//requets
#import "AliyunOSSManager.h"//上传头像
#import "BCUploadImageRequest.h"
#import "BCUpdateUserHeadImageRequest.h"

@interface BCUserHeadPortraitController () <QMUIImagePreviewViewDelegate,QMUIZoomImageViewDelegate>

@property (nonatomic, strong) QMUIImagePreviewView *imagePreviewView;


/**
 *tempHeadImage
 */
@property (nonatomic, copy) UIImage *tempHeadImage;

@end

@implementation BCUserHeadPortraitController

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.view.backgroundColor = [UIColor blackColor];
    self.customNaviBar.backgroundColor = [self.view.backgroundColor colorWithAlphaComponent:.5];
    //
    [self setupSubviews];
    //
    if (!self.headUrl) {
        [self toRightMoreAction];
    }
}
- (void)setupSubviews {
    [self.customNaviBar.rightButton setImage:LOAD_IMAGE(@"user_head_more") forState:UIControlStateNormal];
    //
    self.imagePreviewView = [[QMUIImagePreviewView alloc] initWithFrame:self.view.bounds];
    self.imagePreviewView.delegate = self;
    [self.view addSubview:self.imagePreviewView];
}

- (void)didClickedNaviRightButton {
    [self toRightMoreAction];
}

#pragma mark - QMUIImagePreviewViewDelegate
- (NSUInteger)numberOfImagesInImagePreviewView:(QMUIImagePreviewView *)imagePreviewView {
    return 1;
}
- (void)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView renderZoomImageView:(QMUIZoomImageView *)zoomImageView atIndex:(NSUInteger)index {
    WEAK_SELF
    if (zoomImageView) {
        zoomImageView.delegate = self;
        zoomImageView.emptyView.textLabelTextColor = [UIColor whiteColor];
        zoomImageView.emptyView.actionButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 10, 10);
        zoomImageView.emptyView.actionButtonTitleColor = [UIColor whiteColor];
        zoomImageView.emptyView.actionButton.layer.cornerRadius = 2;
        zoomImageView.emptyView.actionButton.layer.borderColor = [UIColor whiteColor].CGColor;
        zoomImageView.emptyView.actionButton.layer.borderWidth = 1;
    }
    if (self.tempHeadImage) {//这个是临时的用于存储需要上传的头像
        [zoomImageView hideEmptyView];
        zoomImageView.image = self.tempHeadImage;
        return;
    }
    //
    if (!self.headUrl) {//没有头像
        zoomImageView.emptyView.hidden = false;
        [zoomImageView showEmptyViewWithText:BCLocalizedKey(@"Don't set head portrait") detailText:nil buttonTitle:BCLocalizedKey(@"Click to Set") buttonTarget:wself buttonAction:@selector(toRightMoreAction)];
    }else {
        
        if (self.headImage) {
            [zoomImageView hideEmptyView];
            zoomImageView.image = self.headImage;
        }else {//需要重新加载头像
            zoomImageView.image = nil;
            [zoomImageView hideEmptyView];
            [zoomImageView showLoading];
            [zoomImageView.imageView sd_setImageWithURL:[NSURL URLWithString:self.headUrl] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                [zoomImageView hideEmptyView];
                if (image) {
                    zoomImageView.image = image;
                    wself.headImage = image;
                }else {
                    zoomImageView.emptyView.hidden = false;
                    [zoomImageView showEmptyViewWithText:BCLocalizedKey(@"Load Failure") detailText:nil buttonTitle:BCLocalizedKey(@"Clicked to reload") buttonTarget:wself buttonAction:@selector(reloadHeadImageAction)];
                    //
                    if (wself.view) {
                        [QMUITips showError:BCLocalizedKey(@"Load Failure") inView:wself.view hideAfterDelay:1];
                    }
                }
            }];
        }
    }
}
- (void)reloadHeadImageAction {
    [self.imagePreviewView.collectionView reloadData];
}

#pragma mark - QMUIZoomImageViewDelegate
- (void)longPressInZoomingImageView:(QMUIZoomImageView *)zoomImageView {
    [self toRightMoreAction];
}




#pragma mark - action
//右侧按钮点击
- (void)toRightMoreAction {
    WEAK_SELF
    UIAlertController *actionSheetVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //拍照
    UIAlertAction *takePhoto = [UIAlertAction actionWithTitle:BCLocalizedKey(@"user_info_head_take_photo") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [wself toTakePhotoAction];
    }];
    //从手机相册选择
    UIAlertAction *library = [UIAlertAction actionWithTitle:BCLocalizedKey(@"user_info_head_photo_library") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [wself toChoosePhotoAction];
    }];
    //保存图片
    UIAlertAction *savePhoto = [UIAlertAction actionWithTitle:BCLocalizedKey(@"user_info_head_photo_save") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [wself toSavePhotoAction];
    }];
    //
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:BCLocalizedKey(@"general_cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [actionSheetVC addAction:takePhoto];
    [actionSheetVC addAction:library];
    if (self.headImage) {
        [actionSheetVC addAction:savePhoto];
    }
    [actionSheetVC addAction:cancelAction];
    [self.navigationController presentViewController:actionSheetVC animated:true completion:nil];
    
}
//保存图片
- (void)toSavePhotoAction {
    WEAK_SELF
    [[BCSavePhotoManager sharedSave] savePhotoToAlbum:self.headImage complete:^(BOOL success, SavePhotoManagerError *error) {
        if (!error) {
            if (wself.view) {
                NSString *success = BCLocalizedKey(@"general_save_success");
                [QMUITips showSucceed:success inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:success]];
            }
        }else {
            if (error.isAuthorization) {
                //权限问题需要开启权限
                [UIAlertController showPhotoAuthorizationWithController:self];
            }else {
                NSString *errMsg = BCLocalizedKey(@"general_save_failure");
                NSString *details = error.error.localizedDescription;
                if (wself.view) {
                    [QMUITips showError:errMsg detailText:details inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:details]];
                }
            }
        }
    }];
}
//拍照
- (void)toTakePhotoAction {
#if TARGET_IPHONE_SIMULATOR
   NSLog(@"模拟器不支持相机功能");
#else
    WEAK_SELF
    [BCTakePhotoController takePhotoWithPrentingController:self complete:^(UIImage *image) {
        [wself reloadHeadPortraitWithImage:image];
    }];
#endif
}
//选择照片
- (void)toChoosePhotoAction {
    WEAK_SELF
    [BCAlbumController showAlbumWithPrentingController:self complete:^(UIImage *image) {
        [wself reloadHeadPortraitWithImage:image];
    }];;
}
//重新加载新照片
- (void)reloadHeadPortraitWithImage:(UIImage *)image {
    /**
     这里需要给headUrl预设一个值 否则无法加载出图片
     上传成功后在修改回来
     */
    self.headUrl = NSStringFromSelector(@selector(headUrl));
    //
    self.tempHeadImage = image;
    [self.imagePreviewView.collectionView reloadData];
    //
    [self uploadHeadImage];
}

/**
 上传头像 先上传到OSS 在将OSS的链接同步给服务器 即上传完成
 */
- (void)uploadHeadImage {
    [QMUITips showLoading:BCLocalizedKey(@"Uploading") inView:self.view];
    //
//    AliyunOSSPutObject *object = [AliyunOSSPutObject new];
//    object.directoryType = GSCOSSPutDirectoryTypeHeader;
//    object.objectKey = [object uuidObjectKeyForType:GSCPutObjectTypeImagePNG];
////    NSData *imageData = [self.headImage qmui_imageResizedInLimitedSize:<#(CGSize)#> resizingMode:<#(QMUIImageResizingMode)#>]
//    object.uploadingData = UIImagePNGRepresentation(self.headImage);
//    WEAK_SELF
//    [[AliyunOSSManager sharedOSS] putObject:object complete:^(AliyunOSSPutResponseObject *respObj, NSError *error) {
//        if (error) {
//            [QMUITips hideAllTipsInView:wself.view];
//            if (wself.view) {
//                NSString *msg = BCLocalizedKey(@"Upload failure");
//                [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
//            }
//        }
//        if (respObj) {
//            [wself requestUpdateUserHeadImage:respObj.fileURLPath];
//        }
//    }];
    BCUploadImageRequest *request = [BCUploadImageRequest new];
    request.uploadImage = self.tempHeadImage;
    WEAK_SELF
    [request didRequestSuccessed:^(id result, id page) {
        BCUploadImageResponse *resp = result;
        NSString *imageUrl = resp.data.img_url;
        if (imageUrl.length) {
            [wself requestUpdateUserHeadImage:imageUrl];
        }else {
           [QMUITips hideAllTipsInView:wself.view];
            if (wself.view) {
                NSString *errMsg = @"Service Error";
                [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
            }
        }
    }];
    [request didRequestFailed:^(NSError *error) {
        [QMUITips hideAllTipsInView:wself.view];
        [wself showUploadImageError:error];
    }];
    [request requestServer];
}
- (void)showUploadImageError:(NSError *)error {
    WEAK_SELF
    NSString *title = BCLocalizedKey(@"Upload failure");
    NSString *msg = error.domain;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    //
    UIAlertAction *uploadAgain = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Upload again") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [wself uploadHeadImage];
    }];
    [alertController addAction:uploadAgain];
    //
    UIAlertAction *chooseAgain = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Choose again") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [wself didClickedNaviRightButton];
    }];
    [alertController addAction:chooseAgain];
    //
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [wself didClickedNaviLeftButton];
    }];
    [alertController addAction:cancel];
    //
    UIViewController *prentingVC = self;
    if (self.navigationController) {
        prentingVC = self.navigationController;
    }
    [prentingVC presentViewController:alertController animated:true completion:false];
}


//
- (void)requestUpdateUserHeadImage:(NSString *)url {
    BCUpdateUserHeadImageRequest *request = [BCUpdateUserHeadImageRequest new];
    request.uuid = [GeneralParameterManager sharedGeneral].uuid;
    //
    request.images = url;
    //
    WEAK_SELF
    [request didRequestCompleted:^{
        [QMUITips hideAllTipsInView:wself.view];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUpdateUserInfoResponse *resp = result;
        [[BCUserManager sharedUser] updateUserLoginData:resp.data];
        if (wself.view) {
            NSString *success = BCLocalizedKey(@"Upload success");
            [QMUITips showSucceed:success inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:success]];
        }
        //更新头像
        [[SDImageCache sharedImageCache] storeImage:wself.tempHeadImage forKey:url toDisk:true completion:nil];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            [QMUITips showError:error.domain inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:error.domain]];
        }
    }];
    [request requestServer];
}

@end
